package com.zhaowb.springcloud.gate.util;

import com.zhaowb.springcloud.api.vo.log.LogInfo;
import com.zhaowb.springcloud.gate.rpc.ILogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created with IDEA
 * 日志写入线程
 *
 * @author zhaowb
 * @date 2018/11/9 16:29
 */
public class DBLog extends Thread {

    private static final Logger log = LoggerFactory.getLogger(DBLog.class);

    private static DBLog dbLog = null;
    private static BlockingQueue<LogInfo> logInfoQueue = new LinkedBlockingQueue<>(1024);

    private ILogService logService;

    public ILogService getLogService() {
        return logService;
    }

    public DBLog setLogService(ILogService logService) {

        if (this.logService == null) {
            this.logService = logService;
        }
        return this;
    }

    public static synchronized DBLog getInstance() {
        if (dbLog == null) {
            dbLog = new DBLog();
        }
        return dbLog;
    }

    private DBLog() {
        super("CLogMysqlWriterThread");
    }

    public void offerQueue(LogInfo logInfo) {
        try {
            logInfoQueue.offer(logInfo);
        } catch (Exception e) {
            log.info("日志写入失败", e);
        }
    }

    @Override
    public void run() {
        // 缓冲队列
        List<LogInfo> bufferedLogList = new ArrayList<>();
        while (true) {
            try {
                bufferedLogList.add(logInfoQueue.take());
                logInfoQueue.drainTo(bufferedLogList);

                if (bufferedLogList != null && bufferedLogList.size() > 0) {
                    // 写入日志
                    for (LogInfo logInfo : bufferedLogList) {
                        logService.saveLog(logInfo);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();

                // 防止缓冲队列填充数据出现异常刷屏
                try {
                    Thread.sleep(1000);
                } catch (Exception el) {

                }
            } finally {
                if (bufferedLogList != null && bufferedLogList.size() > 0) {
                    try {
                        bufferedLogList.clear();
                    } catch (Exception e) {

                    }
                }
            }
        }
    }
}
